package com.logic.comment.util;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class XSThreadUtil {
    /**
     * 创建并返回一个自定义的线程池
     *
     * @return 返回一个ExecutorService实例
     */
    @Bean(value = "executorService")
    public ExecutorService executorService() {
        return new ThreadPoolExecutor(
                20, // 核心线程数
                20, // 最大线程数
                3600, // 空闲线程存活时间
                TimeUnit.SECONDS, // 时间单位
                new PriorityBlockingQueue<>(2000) // 任务队列
        );
    }

    /**
     * 创建并返回一个自定义的 ScheduledExecutorService
     *
     * @return 返回一个 ScheduledExecutorService 实例
     */
    @Bean(value = "scheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService() {
        AtomicInteger threadCount = new AtomicInteger(1);
        return new ScheduledThreadPoolExecutor(5, r -> {
            Thread thread = new Thread(r);
            thread.setName("Custom-Scheduled-Thread-" + threadCount.getAndIncrement());
            thread.setDaemon(true); // 设置为守护线程
            return thread;
        });
    }
}
